package cn.felord.security.autoconfigure.handler;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;

/**
 * @author felord.cn
 * @since 2021/8/6 18:11
 */
public class SimpleAuthenticationEntryPoint extends ResponseWriter implements AuthenticationEntryPoint {
    private static final Logger log = LoggerFactory.getLogger(SimpleAuthenticationEntryPoint.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        String message = authException.getLocalizedMessage();

        if (InvalidBearerTokenException.class.isAssignableFrom(authException.getClass())) {
            message = "令牌失效，请重新登录";
        } else if (AuthenticationServiceException.class.isAssignableFrom(authException.getClass())) {
            message = "认证服务异常，请稍后再试";
        }
        request.setAttribute("exMsg", message);
        this.write(request, response);
    }

    @Override
    protected SecurityRest<?> body(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        Map<String, String> map = Collections.singletonMap("uri", requestURI);
        String exMsg = (String) request.getAttribute("exMsg");
        if (log.isDebugEnabled()) {
            log.debug("the request for uri: {} is unauthorized, reason: {}", requestURI, exMsg);
        }
        return SecurityRestBody.build(HttpStatus.UNAUTHORIZED.value(), map, exMsg, false);
    }

}
